﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace HttpTest
{
    public static class HttpHelper
    {
        //private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        public static CookieContainer m_CookieContainer;//保存用户登陆状态
        //public static CookieCollection m_CookieCollection;//保存用户的状态
        /// <summary>
        /// HttpWebRequest 发送一个Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PostData(string url, string postData)
        {
            string result = string.Empty;
            try
            {
                System.Net.ServicePointManager.DefaultConnectionLimit = 300;
                System.GC.Collect();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (m_CookieContainer == null)
                {
                    request.CookieContainer = new CookieContainer();
                    m_CookieContainer = request.CookieContainer;
                }
                else
                {
                    if (m_CookieContainer.Count == 0)
                    {
                        request.CookieContainer = new CookieContainer();
                        m_CookieContainer = request.CookieContainer;
                    }
                    else
                    {
                        request.CookieContainer = m_CookieContainer;
                    }
                }
                //request.UseDefaultCredentials = false;
                request.Proxy = null;
                request.CookieContainer = m_CookieContainer;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.AllowAutoRedirect = true;
                request.Timeout = 200000;

                byte[] byte1 = Encoding.UTF8.GetBytes(postData);//最终编码后要上传的数据
                request.ContentLength = postData.Length;

                Stream writeStream = request.GetRequestStream();
                writeStream.Write(byte1, 0, postData.Length);
                writeStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    result = reader.ReadToEnd();
                    stream.Close();
                    reader.Close();
                }
                else
                {
                    result = "";
                }
                response.Close();
                response = null;
                request = null;
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.ToString());
                return "";
            }
            return result;
        }

        /// <summary>
        /// HttpWebRequest 发送一个Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static bool PostDataGzip(string url, string postData, ref string result)
        {
            bool i = false;
            try
            {
                System.Net.ServicePointManager.DefaultConnectionLimit = 300;
                System.GC.Collect();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (m_CookieContainer == null)
                {
                    request.CookieContainer = new CookieContainer();
                    m_CookieContainer = request.CookieContainer;
                }
                else
                {
                    if (m_CookieContainer.Count == 0)
                    {
                        request.CookieContainer = new CookieContainer();
                        m_CookieContainer = request.CookieContainer;
                    }
                    else
                    {
                        request.CookieContainer = m_CookieContainer;
                    }
                }
                //request.UseDefaultCredentials = false;
                request.Proxy = null;
                request.CookieContainer = m_CookieContainer;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
                //request.AutomaticDecompression = DecompressionMethods.GZip;
                request.Referer = "http://order.xiaomi.com/buy/checkout";
                request.Host = "order.xiaomi.com";
                request.AllowAutoRedirect = true;
                request.Timeout = 200000;

                //var bytesToPost = Encoding.Default.GetBytes(postData);
                //var memoryStream = new MemoryStream();
                //var gzipStram = new GZipStream(memoryStream, CompressionMode.Compress, true);
                //gzipStram.Write(bytesToPost, 0, bytesToPost.Length);
                //gzipStram.Close();
                //var mypostdata = memoryStream.ToArray();
                //request.ContentLength = mypostdata.Length;
                //var writeStream = request.GetRequestStream();
                //writeStream.Write(mypostdata, 0, mypostdata.Length);

                byte[] byte1 = Encoding.Default.GetBytes(postData);//最终编码后要上传的数据
                request.ContentLength = postData.Length;
                Stream writeStream = request.GetRequestStream();
                writeStream.Write(byte1, 0, postData.Length);

                writeStream.Close();
                var response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //if (m_CookieCollection == null) { m_CookieCollection = new CookieCollection(); }
                    //m_CookieCollection = response.Cookies;

                    var stream = response.GetResponseStream();
                    var reader = new StreamReader(stream, Encoding.UTF8);
                    result = reader.ReadToEnd();
                    if (stream != null) stream.Close();
                    reader.Close();
                }
                else
                {
                    result = "";
                    i = false;
                }
                response.Close();
                response = null;
                request = null;
                i = true;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                return false;
            }
            return i;
        }
        /// <summary>
        /// HttpWebRequest 发送一个GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static string GetData(string url)
        {
            string result = string.Empty;
            try
            {
                System.Net.ServicePointManager.DefaultConnectionLimit = 300;
                System.GC.Collect();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (m_CookieContainer == null)
                {
                    request.CookieContainer = new CookieContainer();
                    m_CookieContainer = request.CookieContainer;
                }
                else
                {
                    if (m_CookieContainer.Count == 0)
                    {
                        request.CookieContainer = new CookieContainer();
                        m_CookieContainer = request.CookieContainer;
                    }
                    else
                    {
                        request.CookieContainer = m_CookieContainer;
                    }
                }
                //request.UseDefaultCredentials = false;
                request.Proxy = null;
                request.CookieContainer = m_CookieContainer;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.Headers.Add(HttpRequestHeader.IfModifiedSince, "Thu, 1 Jan 1970 00:00:00 GMT");
                //request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
                //string userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
                //request.Headers.Add(HttpRequestHeader.Accept, "*/*");
                //request.Headers.Add(HttpRequestHeader.Connection, "keep-alive");
                //request.Headers.Add(HttpRequestHeader.Referer, "http://sudi.qq.com/web/");
                //request.Headers.Add(HttpRequestHeader.Host, "sudi.qq.com");
                //request.Headers.Add(HttpRequestHeader.UserAgent, userAgent);
                //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
                //request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8");

                request.AllowAutoRedirect = true;
                //request.MaximumAutomaticRedirections = 3;
                request.Timeout = 200000;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    result = reader.ReadToEnd();
                    stream.Close();
                    reader.Close();

                }
                else
                {
                    result = "";
                }
                response.Close();
                response = null;
                request = null;
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.ToString());
                return "";
            }
            return result;
        }

        /// <summary>
        /// HttpWebRequest 发送一个GET请求获取QQ快递
        /// </summary>
        /// <param name="url"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public static string GetDataQQKD(string url)
        {
            string result = string.Empty;
            try
            {
                System.Net.ServicePointManager.DefaultConnectionLimit = 300;
                System.GC.Collect();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (m_CookieContainer == null)
                {
                    request.CookieContainer = new CookieContainer();
                    m_CookieContainer = request.CookieContainer;
                }
                else
                {
                    if (m_CookieContainer.Count == 0)
                    {
                        request.CookieContainer = new CookieContainer();
                        m_CookieContainer = request.CookieContainer;
                    }
                    else
                    {
                        request.CookieContainer = m_CookieContainer;
                    }
                }
                //request.UseDefaultCredentials = false;
                request.Proxy = null;
                request.CookieContainer = m_CookieContainer;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "*/*";
                request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
                request.IfModifiedSince = DateTime.Parse("Thu, 1 Jan 1970 00:00:00 GMT");
                request.Referer = "http://sudi.qq.com/web/";
                //request.Headers.Add(HttpRequestHeader.IfModifiedSince, "Thu, 1 Jan 1970 00:00:00 GMT");
                //request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
                //string userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
                //request.Headers.Add(HttpRequestHeader.Accept, "*/*");
                //request.Headers.Add(HttpRequestHeader.Connection, "keep-alive");
                //request.Headers.Add(HttpRequestHeader.Referer, "http://sudi.qq.com/web/");
                //request.Headers.Add(HttpRequestHeader.Host, "sudi.qq.com");
                //request.Headers.Add(HttpRequestHeader.UserAgent, userAgent);
                //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
                //request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8");

                request.AllowAutoRedirect = true;
                //request.MaximumAutomaticRedirections = 3;
                request.Timeout = 200000;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    result = reader.ReadToEnd();
                    stream.Close();
                    reader.Close();
                }
                else
                {
                    result = "";
                }
                response.Close();
                response = null;
                request = null;
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.ToString());
                return "";
            }
            return result;
        }
    }
}
